from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

from api.models import Token

import json


class TokenMiddleware(MiddlewareMixin):

    def process_request(self, request):
        # 校验token
        if request.path.find('/api') == 0:
            token = request.headers.get('token')
            if not token or not Token.objects.filter(token=token).exists():
                return HttpResponse(json.dumps({
                    'status': 0,
                    'msg': 'token令牌无效，请联系管理员'
                }), content_type="application/json")
